<template>
  <div class="register-container">
    <div class="register-box">
      <h2 class="register-title">注册账号</h2>
      
      <!-- 后端状态指示器 -->
      <div class="backend-status" v-if="backendStatus !== 'online'">
        <el-alert
          v-if="backendStatus === 'checking'"
          title="正在检查服务器连接状态..."
          type="info"
          :closable="false"
          show-icon
        />
        <el-alert
          v-if="backendStatus === 'offline'"
          title="无法连接到后端服务器，请确保服务器已启动"
          type="error"
          :closable="false"
          show-icon
        >
          <template #default>
            <el-button size="small" @click="checkBackendStatus" :loading="backendStatus === 'checking'">
              重试连接
            </el-button>
          </template>
        </el-alert>
      </div>
      
      <!-- 开发者工具 -->
      <div class="dev-tools" v-if="debug">
        <el-collapse>
          <el-collapse-item title="开发者选项" name="1">
            <el-form>
              <el-form-item label="API基础路径">
                <el-input v-model="apiBase" placeholder="例如: http://localhost:3000">
                  <template #append>
                    <el-button @click="testApiBase">测试</el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="注册API路径">
                <el-select v-model="registerPath" placeholder="选择API路径">
                  <el-option
                    v-for="(path, index) in registerApiPaths"
                    :key="index"
                    :label="path.replace(apiBase, '')"
                    :value="path"
                  />
                </el-select>
                <el-button type="primary" size="small" class="ml-2" @click="addCustomPath">添加</el-button>
              </el-form-item>
              <el-form-item v-if="lastError">
                <pre class="error-display">{{ lastError }}</pre>
              </el-form-item>
            </el-form>
          </el-collapse-item>
        </el-collapse>
      </div>
      
      <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" class="register-form">
        <el-form-item prop="username">
          <el-input v-model="registerForm.username" placeholder="用户名">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item prop="email">
          <el-input v-model="registerForm.email" placeholder="邮箱">
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item prop="phone">
          <el-input v-model="registerForm.phone" placeholder="手机号">
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="密码" show-password>
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="确认密码" show-password>
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" class="register-button" @click="handleRegister" :loading="loading">
            注册
          </el-button>
        </el-form-item>
        
        <div class="form-tips">
          <p class="text-xs text-gray-500 mt-2">
            密码需包含至少一个大写字母、一个小写字母和一个数字，长度至少8位
          </p>
          <p class="text-xs text-gray-500 mt-1">
            用户名只能包含字母、数字和下划线，长度为4-20个字符
          </p>
        </div>
      </el-form>
      
      <div class="register-footer">
        <p>已有账号？<router-link to="/login">立即登录</router-link></p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Phone } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const registerFormRef = ref()
const loading = ref(false)
const debug = ref(process.env.NODE_ENV === 'development')
const backendStatus = ref('checking') // 'checking', 'online', 'offline'

// API路径相关
const apiBase = ref('http://localhost:3000')
const registerApiPaths = ref([
  `${apiBase.value}/api/auth/register`,
  `${apiBase.value}/api/users/register`,
  `${apiBase.value}/api/v1/auth/register`,
  `${apiBase.value}/api/v1/users/register`
])
const registerPath = ref(registerApiPaths.value[0])
const lastError = ref('')

// 添加自定义API路径
const addCustomPath = () => {
  const customPath = prompt('请输入自定义API路径', `${apiBase.value}/api/custom/register`)
  if (customPath && !registerApiPaths.value.includes(customPath)) {
    registerApiPaths.value.push(customPath)
    registerPath.value = customPath
  }
}

// 测试API基础路径
const testApiBase = async () => {
  try {
    const response = await axios.get(`${apiBase.value}/api/health`, { timeout: 3000 })
    ElMessage.success(`连接成功: ${response.status}`)
  } catch (error) {
    if (error.response) {
      ElMessage.warning(`服务器响应: ${error.response.status}`)
    } else {
      ElMessage.error('连接失败')
    }
  }
}

// 注册表单数据
const registerForm = reactive({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: ''
})

// 表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名长度应为4-20个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]{4,20}$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码长度不能少于8个字符', trigger: 'blur' },
    { 
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d!@#$%^&*()_+]{8,}$/, 
      message: '密码需包含至少一个大写字母、一个小写字母和一个数字', 
      trigger: 'blur' 
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 检查后端服务状态
const checkBackendStatus = async () => {
  try {
    backendStatus.value = 'checking'
    
    // 尝试不同的健康检查端点
    const checkPaths = [
      'http://localhost:3000/api/health',
      'http://localhost:3000/api/v1/health',
      'http://localhost:3000/api/v1/workflows',
      'http://localhost:3000/api/workflows',
      'http://localhost:3000/health'
    ]
    
    let response = null
    let successPath = ''
    
    // 依次尝试不同的路径
    for (const apiPath of checkPaths) {
      try {
        console.log(`检查后端状态，尝试路径: ${apiPath}`)
        response = await axios.get(apiPath, { timeout: 3000 })
        successPath = apiPath
        console.log(`成功连接到后端, 路径: ${apiPath}`)
        break
      } catch (e) {
        console.log(`路径 ${apiPath} 检查失败:`, e.message)
        // 如果请求失败但有响应，也说明后端在运行
        if (e.response) {
          response = e.response
          successPath = apiPath
          console.log(`后端已响应(${e.response.status}), 路径: ${apiPath}`)
          break
        }
      }
    }
    
    // 如果所有路径都没有响应，则认为后端不在线
    if (!response) {
      throw new Error('所有后端检查路径均无响应')
    }
    
    console.log(`后端状态检查完成，使用路径: ${successPath}，状态码: ${response.status}`)
    backendStatus.value = 'online'
    return true
  } catch (error) {
    console.error('后端服务状态检查失败:', error)
    backendStatus.value = 'offline'
    ElMessage.warning('无法连接到后端服务器，请确保服务器已启动')
    return false
  }
}

// 在组件挂载时检查后端状态
onMounted(async () => {
  await checkBackendStatus()
})

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    loading.value = true
    
    try {
      // 首先检查后端服务是否在线
      const isBackendOnline = await checkBackendStatus()
      if (!isBackendOnline) {
        ElMessage.error('后端服务不可用，无法完成注册')
        loading.value = false
        return
      }
      
      // 提取注册所需数据
      const { confirmPassword, ...userData } = registerForm
      
      // 确保发送给后端的数据符合要求
      const registerData = {
        username: userData.username,
        email: userData.email,
        password: userData.password
      }
      
      // 如果有其他可选字段，也可以添加
      if (userData.phone) {
        registerData.phone = userData.phone
      }
      
      if (debug.value) {
        console.log('注册数据:', registerData)
      }
      
      // 直接使用axios发送请求，绕过userStore
      try {
        console.log('开始发送注册请求...')
        
        // 使用选择的API路径或尝试不同的路径
        let response = null
        let successPath = ''
        lastError.value = ''
        
        if (registerPath.value) {
          // 如果用户选择了特定路径，就只使用这个路径
          console.log(`尝试用户选择的路径: ${registerPath.value}`)
          try {
            response = await axios({
              method: 'post',
              url: registerPath.value,
              data: registerData,
              headers: {
                'Content-Type': 'application/json'
              }
            })
            successPath = registerPath.value
          } catch (err) {
            lastError.value = JSON.stringify(err, null, 2)
            console.error(`用户选择的路径 ${registerPath.value} 请求失败:`, err)
            throw err
          }
        } else {
          // 自动尝试不同的路径
          const apiPaths = registerApiPaths.value
          let lastErr = null
          
          for (const apiPath of apiPaths) {
            try {
              console.log(`尝试路径: ${apiPath}`)
              response = await axios({
                method: 'post',
                url: apiPath,
                data: registerData,
                headers: {
                  'Content-Type': 'application/json'
                },
                timeout: 5000
              })
              
              successPath = apiPath
              console.log(`成功使用路径: ${apiPath}`)
              break
            } catch (e) {
              console.log(`路径 ${apiPath} 请求失败:`, e.message)
              lastErr = e
            }
          }
          
          // 如果所有路径都失败了
          if (!response) {
            lastError.value = JSON.stringify(lastErr, null, 2)
            throw lastErr || new Error('所有API路径请求都失败')
          }
        }
        
        console.log(`注册成功，使用路径: ${successPath}`)
        console.log('注册响应:', response)
        
        if (response.data.success || response.status === 201) {
          ElMessage.success('注册成功，请登录')
          router.push('/login')
        } else {
          throw new Error(response.data.message || '注册失败')
        }
      } catch (err: any) {
        console.error('API请求错误:', err)
        
        let errorMsg = '注册失败，请稍后重试'
        let errorDetails = ''
        
        if (err.message === 'Network Error') {
          errorMsg = '网络错误，请确保后端服务器已启动'
          errorDetails = '无法连接到后端服务器，请检查服务器是否运行在http://localhost:3000'
        } else if (err.response) {
          console.log('错误状态码:', err.response.status)
          console.log('错误数据:', err.response.data)
          
          // 特殊处理常见的注册错误
          if (err.response.status === 409) {
            const errorData = err.response.data
            if (errorData.message?.includes('用户名已被使用')) {
              errorMsg = '用户名已存在，请使用其他用户名'
            } else if (errorData.message?.includes('邮箱已被使用')) {
              errorMsg = '邮箱已被注册，请使用其他邮箱或找回密码'
            } else {
              errorMsg = errorData.message || '注册失败，该账号信息已被使用'
            }
          } else if (err.response.status === 400) {
            errorMsg = '提交的数据格式有误，请检查填写信息'
            if (err.response.data.message) {
              errorDetails = err.response.data.message
            }
          } else {
            // 一般错误处理
            if (typeof err.response.data === 'string') {
              errorMsg = err.response.data
            } else if (err.response.data?.message) {
              errorMsg = err.response.data.message
            } else if (err.response.data?.error) {
              errorMsg = err.response.data.error
            }
          }
          
          // 添加更详细的错误信息
          if (err.response.data?.statusCode && !errorDetails) {
            errorDetails = `错误代码: ${err.response.data.statusCode}`
          }
        } else if (err.message) {
          errorMsg = err.message
        }
        
        ElMessage.error(errorMsg)
        if (errorDetails) {
          console.error(errorDetails)
          ElMessage.warning(errorDetails)
        }
      }
    } catch (error: any) {
      console.error('表单验证或其他错误:', error)
      ElMessage.error('表单验证失败，请检查您的输入')
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.register-box {
  width: 400px;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.register-title {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
  font-size: 24px;
}

.register-form {
  margin-bottom: 20px;
}

.register-button {
  width: 100%;
}

.register-footer {
  text-align: center;
  font-size: 14px;
  color: #606266;
}

.register-footer a {
  color: #409eff;
  text-decoration: none;
}

.form-tips {
  text-align: center;
  font-size: 14px;
  color: #606266;
}

.backend-status {
  margin-bottom: 15px;
}

.backend-status .el-alert {
  margin-bottom: 10px;
}

.dev-tools {
  margin-bottom: 20px;
}

.dev-tools .el-collapse {
  border-top: none;
}

.dev-tools .el-collapse-item__header {
  padding: 0;
}

.dev-tools .el-collapse-item__header .el-collapse-item__header-text {
  font-size: 14px;
  font-weight: bold;
}

.dev-tools .el-collapse-item__content {
  padding: 0;
}

.dev-tools .el-collapse-item__content .el-form {
  padding: 10px;
}

.dev-tools .el-collapse-item__content .el-form .el-form-item {
  margin-bottom: 10px;
}

.dev-tools .el-collapse-item__content .el-form .el-form-item .el-form-item__label {
  font-size: 12px;
}

.dev-tools .el-collapse-item__content .el-form .el-form-item .el-input {
  width: 100%;
}

.dev-tools .el-collapse-item__content .el-form .el-form-item .el-button {
  width: 100%;
}

.dev-tools .el-collapse-item__content .el-form .el-form-item .error-display {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  margin-top: 10px;
}
</style> 